package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.utils.Utils
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.ICON_TRANSFER_NOTIFY
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.MyOrderCurrencyBean
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.PushMsgBean
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.PushMsgManager
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.SstTransferBean
import com.example.wallet.db.UserInfoManager
import ikidou.reflect.TypeBuilder
import org.greenrobot.eventbus.EventBus
import java.lang.reflect.Type

class MyOrderCurrencyFragment : SimpleListFragment<MyOrderCurrencyBean>() {

    companion object {
        fun newInstance(): MyOrderCurrencyFragment {
            val args = Bundle()
            val fragment = MyOrderCurrencyFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var mPushMsgBeans = mutableListOf<PushMsgBean>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val iconPushMsgList = PushMsgManager.getInstance().iconPushMsgList
        mPushMsgBeans.addAll(iconPushMsgList)
//        isEnableLoadMore = false
        isAddDividerItemDecoration = false
    }


    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        mHeader.setBackgroundResource(R.color.bg_color_0)
        addHeader(R.layout.comment_header_layout)
        val mToolbar: Toolbar = mHeader.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.my_order_currency_title)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }
    }

    override fun getItemLayout(): Int {
        return R.layout.my_order_currency_fragment
    }


    override fun convertItem(helper: JssBaseViewHolder?, item: MyOrderCurrencyBean?) {
        val iconTvStr = if (item?.isSeller == 1) "卖 ${item.tokenType}" else "买 ${item?.tokenType}"
        val iconTvColor = if (item?.isSeller == 1) R.color.image_color_red else R.color.PrimaryColor
        helper?.setText(R.id.iconTv, iconTvStr)
            ?.setViewVisible(R.id.mBagView, item?.isShowBagView == true)
            ?.setTextColorRes(R.id.iconTv, iconTvColor)
            ?.setText(R.id.createTv, item?.createTime)
            ?.setText(R.id.statusDesc, item?.orderDesc)
            ?.setText(R.id.single_price_value_Tv, "${item?.price}")
            ?.setText(R.id.txNum, "${item?.txNums}")
            ?.setText(R.id.totalPrice, "${item?.totalPrice}")

    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        super.onItemClick(adapter, view, position)
        hidBag(position)
        val item = mAdapter.getItem(position)
        start(MyOrderResultFragment.newInstance(item?.toid.toString()))

    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(MyOrderCurrencyBean::class.java)
            .endSubType().build()
    }

    override fun netRequest() {
//        val jsonFromRaw =""
//        parseDate(jsonFromRaw)
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "pageCount" to 10,
            "pageIndex" to pageIndex,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryMyTxOrderList)
            .success {
                parseDate(it)
            }.failure {
                onFailed()
            }.error { _, _ ->
                onFailed()
            }.build().post()
    }

    override fun handMessage(msg: MessageWrap?) {
        Log.d("handMessage", "handMessage222: ")
        when (msg?.message) {
            ICON_TRANSFER_NOTIFY -> {
                val iconPushMsgList = PushMsgManager.getInstance().iconPushMsgList
                mPushMsgBeans.clear()
                mPushMsgBeans.addAll(iconPushMsgList)

                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                }
                onRefresh()

            }
            TO_REFRESH_LIST -> {
                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                }
                onRefresh()
            }
        }

    }

    private fun hidBag(pos: Int) {
        val item = mAdapter.getItem(pos)
        item.isShowBagView = false
        mAdapter.notifyItemChanged(pos)
        var index = -10
        for (i in 0 until mPushMsgBeans.size) {
            val pushMsgBean = mPushMsgBeans[i]
            if (pushMsgBean.orderId == item.txNo) {
                index = i
                break
            }

        }
        Log.d("handMessage", "index: $index")
        if (index >= 0) {
            val pushMsgBean = mPushMsgBeans[index]
            mPushMsgBeans.removeAt(index)
            val remove = mPushMsgBeans.remove(pushMsgBean)
            Log.d("handMessage", "remove222: $remove")
        }
    }

    private fun showBag() {
        for (e in mAdapter.data) {
            for (j in mPushMsgBeans) {
                if (e.txNo == j.orderId) {
                    e.isShowBagView = true
                    break
                }
            }
        }
        mAdapter.notifyDataSetChanged()
    }


    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val list = obj["list"]?.toString()
        val array = JSON.parseArray(list, MyOrderCurrencyBean::class.java)
        loadListDate(array)

        showBag()

        delayedTime = 0
    }

    override fun onDestroy() {
        super.onDestroy()
        PushMsgManager.getInstance().addIconPushMsgList(mPushMsgBeans)
        EventBus.getDefault().post(MessageWrap.getInstance(ICON_TRANSFER_NOTIFY))
    }
}